const UserService = require('../service/user');
const WorkerService = require('../service/worker');
const LoggerService = require('../service/logger');
const DbService = require('../service/db2');
const OldDbService = require('../service/db');

const userService = new UserService();
const workerService = new WorkerService();
const tables = [
  'user',
  'worker',
  'tenant',
  'organization',
  'contract',
  'template',
  'send',
  'notice',
  'tenantSignRecord',
  'workerSignRecord',
];

module.exports = app => {
  app.use(async (req, res, next) => {
    const { headers } = req;
    const token = headers['x-token'] || '';

    if (req.path.indexOf('api/') !== -1) {
      // 无需登录的paths
      const noAuthPaths = /\/login|\/mLogin|\/register|\/health|\/common/;
      if (!noAuthPaths.test(req.path)) {
        if (!token) {
          return res.status(401).json({
            code: 401,
          });
        }
        req.token = token;
        if (token) {
          let userInfo;
          if (/h5-api/.test(req.path)) {
            userInfo = await workerService.find(token);
          } else {
            userInfo = await userService.resolveToken(token);
          }
          // eslint-disable-next-line require-atomic-updates
          req.userInfo = userInfo;
        }
      }
    }
    next();
  });

  // error handle
  app.use((err, req, res, next) => {
    const logger = LoggerService.getInstance();
    logger && logger.error && logger.error(err.message);
    if (req.xhr) {
      return res.status(500).json({
        code: 50000,
        msg: err.message,
      });
    }
    next(err);
  });

  app.post(`${process.env.VUE_APP_BASE_API}/common/batchset`, async (req, res) => {
    try {
      const { query, body } = req;
      const { table } = query;
      const { data } = body;
      if (!table) {
        res.json({
          code: 500,
          message: '缺少table参数',
        });
        return;
      }
      if (!data) {
        res.json({
          code: 500,
          message: '缺少data参数',
        });
        return;
      }
      if (tables.includes(table)) {
        const dbService = new DbService(`channel_demo_ess_${table}`);
        let result;
        if (Array.isArray(data)) {
          result = await Promise.all(
            data.map(item => {
              if (item.id) {
                return dbService.upsert(item);
              }
              return Promise.resolve();
            }),
          );
        } else if (typeof data === 'object') {
          result = await Promise.all(Object.entries(data).map(([, item]) => dbService.upsert(item)));
        }
        res.json({
          code: 200,
          message: 'ok',
          result,
        });
        return;
      }
      res.json({
        code: 500,
        message: 'table 参数不合法',
      });
    } catch (err) {
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
  });

  app.post(`${process.env.VUE_APP_BASE_API}/common/batchdel`, async (req, res) => {
    try {
      const { query, body } = req;
      const { table } = query;
      const { data } = body;
      if (!table) {
        res.json({
          code: 500,
          message: '缺少table参数',
        });
        return;
      }
      if (!data) {
        res.json({
          code: 500,
          message: '缺少data参数',
        });
        return;
      }
      if (tables.includes(table) && Array.isArray(data)) {
        const dbService = new DbService(`channel_demo_ess_${table}`);
        const result = await Promise.all(
          data.map(item => {
            const id = item.id || item;
            if (id) {
              return dbService.deleteById(id);
            }
            return Promise.resolve();
          }),
        );
        res.json({
          code: 200,
          message: 'ok',
          result,
        });
        return;
      }
      res.json({
        code: 500,
        message: 'table 参数不合法',
      });
    } catch (err) {
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
  });

  app.get(`${process.env.VUE_APP_BASE_API}/common/query`, async (req, res) => {
    try {
      const { query } = req;
      const { table } = query;
      if (!table) {
        res.json({
          code: 500,
          message: '缺少table参数',
        });
        return;
      }
      if (tables.includes(table)) {
        const dbService = new DbService(`channel_demo_ess_${table}`);
        const dataList = await dbService.selectAll();
        res.json({
          code: 200,
          data: dataList,
          message: 'ok',
        });
        return;
      }
      res.json({
        code: 500,
        message: 'table 参数不合法',
      });
    } catch (err) {
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
  });

  app.get(`${process.env.VUE_APP_BASE_API}/common/oldquery`, async (req, res) => {
    try {
      const { query } = req;
      const { table } = query;
      if (!table) {
        res.json({
          code: 500,
          message: '缺少table参数',
        });
        return;
      }
      if (tables.includes(table)) {
        const oldDbService = new OldDbService();
        const dataList = await oldDbService.hVals(table);
        res.json({
          code: 200,
          data: dataList,
          message: 'ok',
        });
        return;
      }
      res.json({
        code: 500,
        message: 'table 参数不合法',
      });
    } catch (err) {
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
  });
};
